/*
//1. 引入 require , (引入 node)
var http = require("http");

//2.创建服务器  request请求数据，response 接收数据
http.createServer(function (request, response) {
    //发送http头部 http状态值 200 ：OK, 内容类型：‘text/plain’;
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    //发送响应数据
    response.end("ddddd\n");
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

*/

/*

//引入require http, fs, url 为啥引入这些？
var http = require('http');
var fs = require('fs');
var url = require('url');

//看着代码写注释很简单，但是为啥是这样的注释才能理解的更上一个层次；*****
//创建web服务器 web服务器就是接收数据和发送处理后的数据的，所以用参数 request 接收数据，用参数 response 响应发送数据
http.createServer(function (request, response) {
    //接收数据之后，看用户请求的是什么，所以要解析请求，包括文件名
    //如何解析请求？？
    var pathname = url.parse(request.url).pathname;

    //输出请求的文件名
    console.log("request for " + pathname + "received.");

    //先是得到请求的地址，再是从文件系统中读取请求的文件内容
    //substr(1) 是什么意思
    fs.readFile(pathname.substr(1), function (err, data) {
        if (err) {
            console.log(err);
            response.writeHead(404, { 'Content-Type': 'text/html' });
        } else {
            response.writeHead(200, { 'Content-Type': 'text/html' });

            //响应内容
            response.write(data.toString());
        }
        //发送响应数据
        response.end();
    });
}).listen(8888);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8080/');

*/
//真的好了耶


var express = require('express');
var app = express();

// import { createRequire } from 'module';
// const require = createRequire(import.meta.url);

var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "content-type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    if (req.method == "OPTIONS") {
        res.send("200");
    } else {
        next();
    }
});

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'kxq123',
    database: 'mysite'
});

connection.connect();

/** Insert */
function insert(password, name, age) {
    var addSql = 'INSERT INTO user(password, name, age) VALUES(?,?,?)';
    var addSqlParams = [password, name, age];
    connection.query(addSql, addSqlParams, function (err, result) {
        if (err) {
            console.log('[INSERT ERROR] - ', err.message);
            return;
        }

        console.log('--------------------------INSERT----------------------------');
        //console.log('INSERT ID:',result.insertId);        
        console.log('INSERT ID:', result);
        console.log('-----------------------------------------------------------------\n\n');
    });

}


function deleteItem(id) {
    var delSql = 'DELETE FROM user where id  = ' + id;
    //删
    connection.query(delSql, function (err, result) {
        if (err) {
            console.log('[DELETE ERROR] - ', err.message);
            return;
        }

        console.log('--------------------------DELETE----------------------------');
        console.log('DELETE affectedRows', result.affectedRows);
        console.log('-----------------------------------------------------------------\n\n');
    });
}

function updateItem(id, name, age) {
    var modSql = 'UPDATE user SET name = ?,age = ? WHERE Id = ?';
    var modSqlParams = [name, age, id];
    //改
    connection.query(modSql, modSqlParams, function (err, result) {
        if (err) {
            console.log('[UPDATE ERROR] - ', err.message);
            return;
        }
    });
}

app.get('/user/list', function (req, res) {
    var sql = 'SELECT * FROM user';
    connection.query(sql, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }

        res.send(result);
    });

})

app.post('/user/add', function (req, res) {
    // 读取已存在的数据
    let name = req.body.name;
    let age = req.body.age;
    insert('', name, age)
})

app.delete('/user/delete', function (req, res) {
    // 读取已存在的数据
    let id = req.body.id;
    deleteItem(id)
})

app.put('/user/update', function (req, res) {
    // 读取已存在的数据
    let id = req.body.id;
    let name = req.body.name;
    let age = req.body.age;
    updateItem(id, name, age)
})

var server = app.listen(8081, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)

})